package vip.web3.common.utils;

import org.apache.commons.codec.binary.Base64;
import vip.web3.common.exception.RRException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;


public class AES {

    /**
     * 功能描述: 加密
     *
     * @param key : 密钥
     * @param data :  待加密的数据
     * @return 加密后的值
     */
    public static String encrypt(String key, String data) {
        try {
            //加密
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            //初始化，设置为加密
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(Base64.decodeBase64(key), "AES"));
            byte[] result = cipher.doFinal(data.getBytes());
            return Base64.encodeBase64String(result);
        } catch (Exception e) {
            throw new RRException("加密失败", e);
        }
    }

    /**
     * 功能描述: 解密
     *
     * @param key : 密钥
     * @param data :  待解密的数据
     * @return 解密后的值
     */
    public static String decrypt(String key, String data) {
        try {
            //加密
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            //初始化,设置为解密
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64.decodeBase64(key), "AES"));
            byte[] result = cipher.doFinal(Base64.decodeBase64(data));
            return new String(result);
        } catch (Exception e) {
            throw new RRException("解密失败", e);
        }
    }

    public static void main(String[] args) {
        String encrypt = encrypt("PDCvDMCo7IqzWD1za1FyPQ==", "eefcabf340694b1a41b63cf0f31709fb673fc2ffc8d21ce0681ffd0ed6b0c3db");
        System.out.println(encrypt);
    }

}